import fs from 'fs'

/**
 * 封装ide接口提供给AI。其他AI插件可以通过这个接口来调用ide的功能，不允许直接调用ide的功能
 *
 */
export class IDEAgent {
    static inst: IDEAgent = null

    constructor() {
        IDEAgent.inst = this;
    }

    getDesc(): string {
        return "提供一些ide的功能,例如创建一个图片资源,材质资源,场景设置等"
    }

    /**
     * 获取场景数据
     */
    getSceneData() {

    }

    /**
     * 获得一个临时目录。
     * 如果不存在会先创建
     * @returns
     */
    getTempDir() {
        if (!Editor.projectPath)
            return null;
        let TmpDir = Editor.projectPath + '/.layaai/aigc_temp/'
        if (!fs.existsSync(TmpDir)) {
            fs.mkdirSync(TmpDir);
        }
        return TmpDir;
    }

    /**
     * 下载一个外网url地址的图片，缓存到本地临时目录中，文件名为temp.png,临时目录的获取方法为this.getTempDir.返回值为文件路径
     * @param url
     * @return path
     */
    async download_img_from_url(url: string,randpath=false): Promise<string> {
        if(!url.startsWith("http")){
            return url;
        }
        let TmpDir = this.getTempDir();
        if (TmpDir.endsWith('/')) TmpDir = TmpDir.substring(0, TmpDir.length - 1);
        let file = `${TmpDir}/temp${randpath?`_${Date.now()}`:''}.png`

        let buffer: any;
        // 通过fetch下载图片文件,得到图片中的数据、
        let response: Response = await fetch(url);
        if(response.ok){
            const buff = await response.arrayBuffer();
            buffer = Buffer.from(buff);
        }
        fs.writeFileSync(file, buffer)
        return file;
    }

    getProjectDir() {
        return Editor.projectPath
    }


    async saveBuffToTmp(buff: Buffer,type:"png"|"jpg"|'mp3'|'wav'="png"){
        //计算buffer的md5 hash
        let crypto = require('crypto');
        let md5 = crypto.createHash('md5');
        let hash = md5.update(buff).digest('hex');
        let TmpDir = this.getTempDir();
        if(TmpDir.endsWith('/')) TmpDir=TmpDir.substring(0,TmpDir.length-1);
        let file = `${TmpDir}/${hash}.${type}`
        fs.writeFileSync(file, buff)
        return file;
    }

    /**
     * 创建一个图片资源
     * name是资源名称，可以有路径，这个是相对项目的路径，例如"assets/abc.png" 不能是绝对路径
     */
    async crateAssetFromFile(filePath:string, name: string) {
        //创建一个资源 第一个参数是相对于项目目录的，第二个是源
        let asset = await Editor.assetDb.writeFile(name, filePath, true);
        return asset;
    }

    async crateAIAssetFromFile(filePath:string, type:string, name: string) {
        //创建一个资源 第一个参数是相对于项目目录的，第二个是源
        let asset = await Editor.assetDb.writeFile('aigc/'+type+'/'+name, filePath, true);
        return asset;
    }

    /**
     * 加载一个图片资源，返回base64编码的字符串
     * @param assetname 资源名称
     */
    async load_asset_img_base64(assetname: string) {
        let asset = await Editor.assetDb.getAsset(assetname);
        try {
            let assetFile = Editor.assetDb.getFullPath(asset);
            let fbuff = fs.readFileSync(assetFile);
            // 将Buffer对象转换为base64编码的字符串
            const base64Str = Buffer.from(fbuff).toString('base64');
            return base64Str;
        } catch (e) {
            console.log(e)
        }
        return undefined;
    }

    //演示函数
    showAIPropUI(name:string){
        Editor.panelManager?.showPanel(name);
    }
    hideAIPropUI(name:string){
        Editor.panelManager?.hidePanel(name);
    }

    // 提供给AI的接口功能

    //判断是否是内部资源
    async isInnerAsset(uuid: string) {
        return ((await Editor.assetDb.getAsset(uuid)).flags & IEditor.AssetFlags.Readonly)!=0;
    }

    getUserToken() {
        return this._userinfo.storeToken
        // let config = new IEditor.conf(Editor.userDataPath, "appconfig");
        // //注意这个可能已经无效了
        // let token = config.get("TOKEN");
        // return token;
    }

    init(){
        let uinfo = Editor.accountManager.userInfo;
        this.storeToken = Editor.accountManager.storeToken;
        let storeToken = this.storeToken;
        this._userinfo = uinfo;    
        this._safeUserData.userId=uinfo.userId;
        this._safeUserData.storeToken = storeToken;
    }

    private _safeUserData:any={}
    private _userinfo:any=null;
    storeToken:string=null;

    getSafeUserData(){
        return this._safeUserData;
    }

    getUserID(){
        return this._userinfo.userId;
    }

    async loadAIInfo(uuid:string):Promise<any>{
        //根据uuid找到资源文件
        let asset = await Editor.assetDb.getAsset(uuid);
        if (!asset){
            console.log('getAssetMetaData_AI: asset not found',uuid);
            return null;
        }

        let filepath = Editor.assetDb.getFullPath(asset)+'.meta';
        let cont = fs.readFileSync(filepath, { encoding: 'utf8' });
        return JSON.parse(cont).aigc;
    }

    async setAIInfo(uuid:string,aidata:any, format=true){
        let asset = await Editor.assetDb.getAsset(uuid);
        if (!asset){
            console.log('saveAssetMetaData_AI: asset not found',uuid);
            return;
        }

        let filepath = Editor.assetDb.getFullPath(asset)+'.meta';
        let cont = fs.readFileSync(filepath, { encoding: 'utf8' });
        let meta = JSON.parse(cont);
        meta.aigc = aidata;
        fs.writeFileSync(filepath, JSON.stringify(meta,null,format?'\t':null));
    }

    async installPlugin(pluginName:string){

        if(pluginName=='layatree'){
            return true;
        }
        return false
    }
}

/**
 * AI代理模拟一个摄像机
 */
export class SceneEditorAgent{

}
